package api

import (
	"context"
	"fmt"
	model "service/model/crm_order"
	kbModel "service/model/kb_pro"
	"time"

	gpb "gitee.com/cloudapex/protos/crm_order/pb"
	kbGpb "gitee.com/cloudapex/protos/pro_know/pb"
	"gitee.com/cloudapex/ulern/util"
)

//创建用户信息（有则不创建，无则创建）
func CreatStu(ctx context.Context, phone string) (*gpb.AccountCreateRes, error) {
	infoReq := &gpb.AccountGetReq{
		Phone: phone,
	}
	infoRes, err := model.StudentInfo.StudentAccountGet(ctx, infoReq)
	util.Debug("%s", infoRes)
	if err != nil {
		util.Debug("%s", err)
		return nil, err
	}
	if infoRes.StudentId == 0 {
		accountReq := &gpb.AccountCreateReq{
			Phone:   phone,
			Pass:    util.MD5s(phone),
			Email:   "",
			Address: "",
		}
		infoRes, err = model.StudentInfo.StudentAccountCreate(ctx, accountReq)
		if err != nil {
			util.Debug("%s", err)
			return nil, err
		}
	}
	return infoRes, nil
}

//根据班型id和用户手机号进行开课（金卡开课）结束时间(*kbGpb.Class, error)
func ClassOpen(ctx context.Context, phone string, timeend int64, userClassIdList []int64) {
	//  创建用户并获取信息
	userInfo, err := CreatStu(ctx, phone)
	if err != nil || userInfo == nil {
		fmt.Sprintln(err)
		return
	}
	for _, v := range userClassIdList {

		classInfo, err := GetClassInfo(ctx, v)

		if err != nil {
			util.Debug("%s", err)
			return
		}
		userreq := &gpb.UserClassReq{
			UserClass: &gpb.UserClass{
				Phone: phone,
				CId:   classInfo.Id,
			},
		}
		userres, _ := model.UserClass.GetUserClass(ctx, userreq)
		if userres.UserClass.Id == 0 {
			if timeend == 0 {
				timeend = time.Now().AddDate(0, int(classInfo.ValidTeam), 0).Unix()
			}
			userreq := &gpb.UserClassReq{
				UserClass: &gpb.UserClass{
					Phone:   phone,
					CId:     classInfo.Id,
					CName:   classInfo.Name,
					At:      time.Now().Unix(),
					CloseAt: timeend,
					State:   -1,
				},
			}
			_, err := model.UserClass.AddUserClass(ctx, userreq)
			if err != nil {
				return
			}

		} else {
			if timeend == 0 {
				timeend = time.Now().AddDate(0, int(classInfo.ValidTeam), 0).Unix()
			}
			userreq := &gpb.UserClassReq{
				UserClass: &gpb.UserClass{
					Id:      userres.UserClass.Id,
					Phone:   phone,
					CId:     classInfo.Id,
					CloseAt: timeend,
					CName:   classInfo.Name,
					At:      time.Now().Unix(),
					State:   -1,
				},
			}

			_, err := model.UserClass.EditUserClass(ctx, userreq)
			if err != nil {
				return
			}
		}

	}
}
func ClassClose(ctx context.Context, phone string, userClassIdList []int64) {
	for _, value := range userClassIdList {
		userreq := &gpb.UserClassReq{
			UserClass: &gpb.UserClass{
				Phone:   phone,
				CId:     value,
				State:   1,
				CloseAt: time.Now().Unix(),
			},
		}

		_, err := model.UserClass.EditUserClass(ctx, userreq)
		if err != nil {
			return
		}
	}

}

//与金卡开课不同，普通开课（开通班型，统计班型学员数量）
func ClassOpenNormal(ctx context.Context, info *gpb.CrmOrderInfoRes, res *gpb.CrmOrderCreateRes, classInfo *kbGpb.Class) (bool, error) {

	userreq := &gpb.UserClassReq{
		UserClass: &gpb.UserClass{
			CId:   info.ClassId,
			Phone: res.Phone,
		},
	}
	userres, _ := model.UserClass.GetUserClass(ctx, userreq)
	if userres.UserClass.Id == 0 {
		userreq := &gpb.UserClassReq{
			UserClass: &gpb.UserClass{
				Phone:     res.Phone,
				CId:       info.ClassId,
				CName:     info.ClassName,
				OrderNo:   res.BillNo,
				RealPrice: int64(info.Price),
				At:        time.Now().Unix(),
				CloseAt:   time.Now().AddDate(0, int(classInfo.ValidTeam), 0).Unix(),
				State:     0,
			},
		}
		_, err := model.UserClass.AddUserClass(ctx, userreq)
		if err != nil {
			util.Debug("开课失败：%s", err)
			return false, err
		}

		calssReq := &kbGpb.ClassReq{
			Id: info.ClassId,
		}
		_, err = kbModel.ProClass.UpdateClassCount(ctx, calssReq)
		if err != nil {
			util.Debug("更新班型学员数量失败：%s", err)
			util.Debug("班型id：", info.ClassId)
			return false, err
		}

	} else {

		userreq := &gpb.UserClassReq{
			UserClass: &gpb.UserClass{
				Id:      userres.UserClass.Id,
				CloseAt: time.Now().AddDate(0, int(classInfo.ValidTeam), 0).Unix(),
			},
		}
		_, err := model.UserClass.EditUserClass(ctx, userreq)
		if err != nil {
			util.Debug("编辑学员班型失败：%s", err)
			return false, err
		}
	}
	return true, nil
}

//********************************************************************************************************************
//  移除相同的班型id
func RemoveSameId(classes []*gpb.UserClass, userClassIdList []int64) (addUserClassIdList []int64) {
	if classes == nil || len(classes) == 0 {
		addUserClassIdList = userClassIdList
	} else {
		for _, ucf := range userClassIdList {
			bo := true
			for _, cf := range classes {
				if ucf == cf.CId {
					bo = false
				}
			}
			if bo {
				addUserClassIdList = append(addUserClassIdList, ucf)
			}
		}

	}
	return
}

//  根据 用户手机号获取有效的班型信息
func getHasUserClass(phone string, ctx context.Context) ([]*gpb.UserClass, error) {
	req := &gpb.UserClassListReq{
		UserClass: &gpb.UserClass{
			Phone:   phone,
			CloseAt: time.Now().Unix(),
		},
		Page:  1,
		Count: 100,
	}
	resUserClass, err := model.UserClass.GetUserClassList(ctx, req)
	if err != nil || resUserClass == nil && resUserClass.UserClass != nil || len(resUserClass.UserClass) == 0 {
		return nil, nil
	}

	return resUserClass.UserClass, nil
}

//获取班型信息
func GetClassInfo(ctx context.Context, id int64) (*kbGpb.Class, error) {

	var proclas kbGpb.ProClassReq
	var class kbGpb.Class
	var pro kbGpb.Project
	class.Id = id
	proclas.Class = &class
	proclas.Pro = &pro
	prolist := kbGpb.ProListReq{ProClassReq: &proclas, Page: 1, Count: 1}
	rep, err := kbModel.ProClass.GetProClassList(ctx, &prolist)
	if err != nil {
		util.Debug("%s", err)
		return &kbGpb.Class{}, err
	}
	classInfo := rep.ProList[0].Class
	return classInfo, nil

}
